import {Component, OnDestroy, NgZone } from '@angular/core';
import { IonicApp, Platform } from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import {ToastController } from 'ionic-angular';
import {Location} from '@angular/common';
import {LocalstorageProvider} from '../providers/localstorage/localstorage';
import {Network} from '@ionic-native/network';
import vconsole from 'vconsole'
import { CodePush, InstallMode } from '@ionic-native/code-push';
import {Tools} from "../tools/tools";
import { Router } from"@angular/router";
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Injectable } from '@angular/core';

@Component({
  templateUrl: 'app.html'
})
@Injectable()
export class MyApp extends Tools implements OnDestroy {
  public static backButtonPressedOnceToExit = false;
  private devFlag: Boolean
  private connectServer = {
    test1: 'http://192.168.7.129:8686', // yazhao
    test2: 'http://192.168.7.113:8686', // haojie
    test3: 'http://192.168.7.125:8686', // xue
    test4: 'http://192.168.0.100:8686', // xinli
    test5: 'http://192.168.7.192:8686'
  };
  private disconnectSubscription

  constructor(public platform: Platform,
              private statusBar: StatusBar,
              splashScreen: SplashScreen,
              private toastCtrl: ToastController,
              private location: Location,
              private loc: LocalstorageProvider,
              private zone: NgZone,
              private codePush: CodePush,
              protected route: Router,
              protected network: Network,
              protected nativePageTransitions: NativePageTransitions,
              private app: IonicApp
  ) {
    super(route, nativePageTransitions, network)
    var that = this;

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      // statusBar.styleDefault();
      statusBar.backgroundColorByHexString("#4584ff")
      splashScreen.hide();

      this.checkdev();
      this.getdebug((debug) => {
        this.checkCodePush(debug)
      })

      // 双击返回按键退出应用
      platform.registerBackButtonAction(function (e) {
        if (location.path() == '/' || location.path() == '/home' || location.path() == '/login') {
          if (MyApp.backButtonPressedOnceToExit) {
            platform.exitApp();
          } else {
            MyApp.backButtonPressedOnceToExit = true;
            let toast = toastCtrl.create({
              message: '再按一次退出',
              duration: 2000,
              position: 'bottom'
            });
            toast.present();
            setTimeout(function () {
              MyApp.backButtonPressedOnceToExit = false;
            }, 2000)
          }
        }else {
          // window.location.replace(document.referrer)
          // that.location.back()
          if (document.referrer == '') {
            that.openPage('home')
          } else {
            that.location.back()
            // history.back();
          }
        }
      }, 101)
    });


  }

  checkCodePush(debug) {

    //如果不是真机环境return
    if (!this.isMobile()) return;
    //发布的key
    let deploymentKey = this.getDeploymentKey(debug)

    this.codePush.sync({
      deploymentKey: deploymentKey,
      updateDialog: {
        updateTitle: "升级提示",
        optionalInstallButtonLabel: '更新',
        optionalIgnoreButtonLabel: '忽略',
        mandatoryUpdateMessage: '有新版本可用，请及时更新\n',
        mandatoryContinueButtonLabel: "更新",
        descriptionPrefix: '更新日志:',
        appendReleaseDescription: true
      },
      installMode: InstallMode.IMMEDIATE
    }).subscribe(data => {
        console.log('更新回调',data)
      });
  }

  checkdev() {
    if (!this.isMobile()) {
      // 非手机环境 开启开发菜单
      // new vconsole()
      this.zone.run(() => {
        this.devFlag = true // debug 版本开启开发菜单
      })
    } else {
      this.zone.run(() => {
        this.getdebug((debug) => {
          this.devFlag = debug;
          if (debug) {
            new vconsole()
          }
        })
      })
    }

  }

  changeserve() {
    if (this.location.path() !== '/login') {
      this.toastCtrl.create({
        message: '请先退出登录，再进行切换环境',
        position: 'top',
        duration: 1000
      }).present();
      return false
    }
    var flag = this.loc.get("developFlag")
    this.loc.set("developFlag", !flag)
    this.toastCtrl.create({
      message: '切换成功',
      position: 'top',
      duration: 1000
    }).present();
  }

  showconsole() {
    const vconsoleEle = document.getElementById('__vconsole')
    const vmaskEle = document.querySelectorAll('.vc-mask')[0] as HTMLElement;
    const panel = document.getElementsByClassName('vc-panel')[0] as HTMLElement;
    if (vconsoleEle) {
      vconsoleEle.className += ' vc-toggle'
      vconsoleEle.style.display = 'block';
      vmaskEle.style.display = 'block';
      panel.style.display = 'block'
    }
  }

  showprompt() {
    // 显示当前的请求地址
    var serverAddress = this.getServeAddress()
    this.toastCtrl.create({
      message: `当前请求地址： ${serverAddress}`,
      position: 'top',
      duration: 1000
    }).present();
  }

  // 获取请求地址
  getServeAddress() {
    var result: String
    var subdomain = this.loc.get('subdomain')
    var developFlag = this.loc.get("developFlag")
    if (!subdomain) {
      if (developFlag) {
        result = 'http://*.wenshidata.com';
      } else {
        result = 'http://*.iemes.cn';
      }
    } else {
      if (subdomain.indexOf('test') > -1) {
        result = this.connectServer[subdomain] || '未知地址'
      } else {
        if (developFlag) {
          result = `http://${subdomain}.wenshidata.com`;
        } else {
          result = `http://${subdomain}.iemes.cn`;
        }
      }
    }

    return result;
  }

  ngOnDestroy() {
    // die
    this.disconnectSubscription.unsubscribe()
  }
}
